package com.example.data_receiver.config;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;

// 自定义请求包装类，用于过滤请求体中的非法字符
public class IllegalCharacterRequestWrapper extends HttpServletRequestWrapper {

    // 定义非法字符的正则表达式
    private static final String regexStr = "[^a-zA-Z0-9\\u4e00-\\u9fa5\\p{P}]";
    private final String filteredBody;

    public IllegalCharacterRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        StringBuilder body = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                body.append(line);
            }
        }
        // 过滤请求体中的非法字符
        this.filteredBody = filterIllegalCharacters(body.toString());
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(filteredBody.getBytes(StandardCharsets.UTF_8));
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return byteArrayInputStream.available() == 0;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
                // 可以根据需要实现
            }

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(filteredBody.getBytes(StandardCharsets.UTF_8))));
    }

    // 过滤非法字符的方法
    private String filterIllegalCharacters(String input) {
        if (input == null) {
            return null;
        }
        // 替换非法字符为空字符串
        return input.replaceAll(regexStr, "");
    }
}    